<!DOCTYPE html>
<!-- saved from url=(0051)http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html -->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh" lang="zh"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="author" content="Clinton Begin">
    <meta name="author" content="Nan Lei">
    <meta name="author" content="Dongxu Wang">
    <meta name="Date-Revision-yyyymmdd" content="20160517">
    <meta http-equiv="Content-Language" content="zh">
    <title>mybatis – MyBatis 3 | Mapper XML 文件</title>
    <link rel="stylesheet" href="./mybatis – MyBatis 3 _ Mapper XML 文件_files/apache-maven-fluido-1.5.min.css">
    <link rel="stylesheet" href="./mybatis – MyBatis 3 _ Mapper XML 文件_files/site.css">
    <link rel="stylesheet" href="./mybatis – MyBatis 3 _ Mapper XML 文件_files/print.css" media="print">

      
    <script type="text/javascript" src="./mybatis – MyBatis 3 _ Mapper XML 文件_files/apache-maven-fluido-1.5.min.js"></script>

                      </head>
        <body class="topBarDisabled">
          
        
    
        <div class="container-fluid">
          <div id="banner">
        <div class="pull-left">
                                <div id="bannerLeft">
                <h2>mybatis</h2>
                </div>
                      </div>
        <div class="pull-right">                                <a href="http://www.mybatis.org/" id="bannerRight" title="MyBatis logo">
                                                                                        <img src="./mybatis – MyBatis 3 _ Mapper XML 文件_files/mybatis-logo.png" alt="MyBatis logo">
                </a>
      </div>
        <div class="clear"><hr></div>
      </div>

      <div id="breadcrumbs">
        <ul class="breadcrumb">
              
                  <li id="publishDate">最近更新: 17 五月 2016
                      <span class="divider">|</span>
                   </li>
                  <li id="projectVersion">版本: 3.4.1-SNAPSHOT
                      </li>
                      
              
      
                            </ul>
      </div>

            
      <div class="row-fluid">
        <div id="leftColumn" class="span2">
          <div class="well sidebar-nav">
              
                <ul class="nav nav-list">
                    <li class="nav-header">参考文档</li>
                              
      <li>
  
                          <a href="http://www.mybatis.org/mybatis-3/zh/index.html" title="简介">
          <span class="none"></span>
        简介</a>
            </li>
                
      <li>
  
                          <a href="http://www.mybatis.org/mybatis-3/zh/getting-started.html" title="入门">
          <span class="none"></span>
        入门</a>
            </li>
                                                                                                                                                                                                                  
      <li>
  
                          <a href="http://www.mybatis.org/mybatis-3/zh/configuration.html" title="XML配置">
          <span class="icon-chevron-right"></span>
        XML配置</a>
                  </li>
                                                                                                                                                                
      <li class="active">
  
            <a href="http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html#"><span class="icon-chevron-down"></span>XML映射文件</a>
                  <ul class="nav nav-list">
                    
      <li>
  
                          <a href="http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html#select" title="查询(select)">
          <span class="none"></span>
        查询(select)</a>
            </li>
                    
      <li>
  
                          <a href="http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html#insert_update_and_delete" title="更新(insert, update and delete)">
          <span class="none"></span>
        更新(insert, update and delete)</a>
            </li>
                    
      <li>
  
                          <a href="http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html#Parameters" title="参数(Parameters)">
          <span class="none"></span>
        参数(Parameters)</a>
            </li>
                    
      <li>
  
                          <a href="http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html#Result_Maps" title="结果集(Result Maps)">
          <span class="none"></span>
        结果集(Result Maps)</a>
            </li>
                    
      <li>
  
                          <a href="http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html#Auto-mapping" title="自动映射(Auto-mapping)">
          <span class="none"></span>
        自动映射(Auto-mapping)</a>
            </li>
                    
      <li>
  
                          <a href="http://www.mybatis.org/mybatis-3/zh/sqlmap-xml.html#cache" title="cache">
          <span class="none"></span>
        cache</a>
            </li>
              </ul>
        </li>
                
      <li>
  
                          <a href="http://www.mybatis.org/mybatis-3/zh/dynamic-sql.html" title="动态SQL">
          <span class="none"></span>
        动态SQL</a>
            </li>
                                                                                    
      <li>
  
                          <a href="http://www.mybatis.org/mybatis-3/zh/java-api.html" title="Java API">
          <span class="icon-chevron-right"></span>
        Java API</a>
                  </li>
                
      <li>
  
                          <a href="http://www.mybatis.org/mybatis-3/zh/statement-builders.html" title="SQL语句构建器">
          <span class="none"></span>
        SQL语句构建器</a>
            </li>
                
      <li>
  
                          <a href="http://www.mybatis.org/mybatis-3/zh/logging.html" title="日志">
          <span class="none"></span>
        日志</a>
            </li>
                              <li class="nav-header">项目文档</li>
                                                                                                                                                                                                                                                                                      
      <li>
  
                          <a href="http://www.mybatis.org/mybatis-3/zh/project-info.html" title="项目信息">
          <span class="icon-chevron-right"></span>
        项目信息</a>
                  </li>
                                                                                                                                                                                                                                                                                          
      <li>
  
                          <a href="http://www.mybatis.org/mybatis-3/zh/project-reports.html" title="项目报表">
          <span class="icon-chevron-right"></span>
        项目报表</a>
                  </li>
            </ul>
              
                
          <hr>

           <div id="poweredBy">
                            <div class="clear"></div>
                            <div class="clear"></div>
                            <div class="clear"></div>
                            <div class="clear"></div>
                             <a href="http://maven.apache.org/" title="构建依靠 Maven" class="poweredBy">
        <img class="builtBy" alt="构建依靠 Maven" src="./mybatis – MyBatis 3 _ Mapper XML 文件_files/maven-feather.png">
      </a>
                  </div>
          </div>
        </div>
        
                
        <div id="bodyColumn" class="span10">
                                  
            

  
    <div class="section">
<h2><a name="Mapper_XML_"></a>Mapper XML 文件</h2>
      
<p>MyBatis 的真正强大在于它的映射语句，也是它的魔力所在。由于它的异常强大，映射器的 XML 文件就显得相对简单。如果拿它跟具有相同功能的 JDBC 代码进行对比，你会立即发现省掉了将近 95% 的代码。MyBatis 就是针对 SQL 构建的，并且比普通的方法做的更好。</p>
      
<p>SQL 映射文件有很少的几个顶级元素（按照它们应该被定义的顺序）：</p>
      
<ul>
        
<li>
          <tt>cache</tt>
          – 给定命名空间的缓存配置。
        </li>
        
<li>
          <tt>cache-ref</tt>
          – 其他命名空间缓存配置的引用。
        </li>
        
<li>
          <tt>resultMap</tt>
          – 是最复杂也是最强大的元素，用来描述如何从数据库结果集中来加载对象。
        </li>
        
<li>
          <s>
            </s><tt><s>parameterMap</s></tt><s>
            – 已废弃！老式风格的参数映射。内联参数是首选,这个元素可能在将来被移除，这里不会记录。
          </s>
        </li>
        
<li>
          <tt>sql</tt>
          – 可被其他语句引用的可重用语句块。
        </li>
        
<li>
          <tt>insert</tt>
          – 映射插入语句
        </li>
        
<li>
          <tt>update</tt>
          – 映射更新语句
        </li>
        
<li>
          <tt>delete</tt>
          – 映射删除语句
        </li>
        
<li>
          <tt>select</tt>
          – 映射查询语句
        </li>
      </ul>
      
<p>下一部分将从语句本身开始来描述每个元素的细节。</p>

      <a name="select"></a>
<div class="section" id="select">
<h3><a name="select"></a>select</h3>
        
<p>查询语句是 MyBatis 中最常用的元素之一，光能把数据存到数据库中价值并不大，如果还能重新取出来才有用，多数应用也都是查询比修改要频繁。对每个插入、更新或删除操作，通常对应多个查询操作。这是 MyBatis 的基本原则之一，也是将焦点和努力放到查询和结果映射的原因。简单查询的 select 元素是非常简单的。比如：
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;select</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"selectPerson"</span><span class="pln"> </span><span class="atn">parameterType</span><span class="pun">=</span><span class="atv">"int"</span><span class="pln"> </span><span class="atn">resultType</span><span class="pun">=</span><span class="atv">"hashmap"</span><span class="tag">&gt;</span><span class="pln">
  SELECT * FROM PERSON WHERE ID = #{id}
</span><span class="tag">&lt;/select&gt;</span></pre></div>

        
<p>这个语句被称作 selectPerson，接受一个 int（或 Integer）类型的参数，并返回一个 HashMap 类型的对象，其中的键是列名，值便是结果行中的对应值。
        </p>

        
<p>注意参数符号：</p>

        
<div class="source"><pre class="prettyprint"><span class="com">#{id}</span></pre></div>

        
<p>这就告诉 MyBatis 创建一个预处理语句参数，通过 JDBC，这样的一个参数在 SQL 中会由一个“?”来标识，并被传递到一个新的预处理语句中，就像这样：
        </p>

        
<div class="source"><pre class="prettyprint"><span class="com">// Similar JDBC code, NOT MyBatis…</span><span class="pln">
</span><span class="typ">String</span><span class="pln"> selectPerson </span><span class="pun">=</span><span class="pln"> </span><span class="str">"SELECT * FROM PERSON WHERE ID=?"</span><span class="pun">;</span><span class="pln">
</span><span class="typ">PreparedStatement</span><span class="pln"> ps </span><span class="pun">=</span><span class="pln"> conn</span><span class="pun">.</span><span class="pln">prepareStatement</span><span class="pun">(</span><span class="pln">selectPerson</span><span class="pun">);</span><span class="pln">
ps</span><span class="pun">.</span><span class="pln">setInt</span><span class="pun">(</span><span class="lit">1</span><span class="pun">,</span><span class="pln">id</span><span class="pun">);</span></pre></div>

        
<p>当然，这需要很多单独的 JDBC 的代码来提取结果并将它们映射到对象实例中，这就是 MyBatis 节省你时间的地方。我们需要深入了解参数和结果映射，细节部分我们下面来了解。
        </p>

        
<p>select 元素有很多属性允许你配置，来决定每条语句的作用细节。
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;select</span><span class="pln">
  </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"selectPerson"</span><span class="pln">
  </span><span class="atn">parameterType</span><span class="pun">=</span><span class="atv">"int"</span><span class="pln">
  </span><span class="atn">parameterMap</span><span class="pun">=</span><span class="atv">"deprecated"</span><span class="pln">
  </span><span class="atn">resultType</span><span class="pun">=</span><span class="atv">"hashmap"</span><span class="pln">
  </span><span class="atn">resultMap</span><span class="pun">=</span><span class="atv">"personResultMap"</span><span class="pln">
  </span><span class="atn">flushCache</span><span class="pun">=</span><span class="atv">"false"</span><span class="pln">
  </span><span class="atn">useCache</span><span class="pun">=</span><span class="atv">"true"</span><span class="pln">
  </span><span class="atn">timeout</span><span class="pun">=</span><span class="atv">"10000"</span><span class="pln">
  </span><span class="atn">fetchSize</span><span class="pun">=</span><span class="atv">"256"</span><span class="pln">
  </span><span class="atn">statementType</span><span class="pun">=</span><span class="atv">"PREPARED"</span><span class="pln">
  </span><span class="atn">resultSetType</span><span class="pun">=</span><span class="atv">"FORWARD_ONLY"</span><span class="tag">&gt;</span></pre></div>

        
<table border="0" class="table table-striped"><caption>Select Attributes</caption>
          
          <thead>
            
<tr class="a">
              
<th>属性</th>
              
<th>描述</th>
            </tr>
          </thead>
          <tbody>
            
<tr class="b">
              
<td><tt>id</tt></td>
              
<td>
              在命名空间中唯一的标识符，可以被用来引用这条语句。
              </td>
            </tr>
            
<tr class="a">
              
<td><tt>parameterType</tt></td>
              
<td>
              将会传入这条语句的参数类的完全限定名或别名。这个属性是可选的，因为 MyBatis 可以通过 TypeHandler 推断出具体传入语句的参数，默认值为 unset。
              </td>
            </tr>
            
<tr class="b">
              
<td>
                <s>parameterMap</s>
              </td>
              
<td>
                <s>这是引用外部 parameterMap 的已经被废弃的方法。使用内联参数映射和 parameterType 属性。
                </s>
              </td>
            </tr>
            
<tr class="a">
              
<td><tt>resultType</tt></td>
              
<td>从这条语句中返回的期望类型的类的完全限定名或别名。注意如果是集合情形，那应该是集合可以包含的类型，而不能是集合本身。使用 resultType 或 resultMap，但不能同时使用。
              </td>
            </tr>
            
<tr class="b">
              
<td><tt>resultMap</tt></td>
              
<td>外部 resultMap 的命名引用。结果集的映射是 MyBatis 最强大的特性，对其有一个很好的理解的话，许多复杂映射的情形都能迎刃而解。使用 resultMap 或 resultType，但不能同时使用。
              </td>
            </tr>
            
<tr class="a">
              
<td><tt>flushCache</tt></td>
              
<td>将其设置为 true，任何时候只要语句被调用，都会导致本地缓存和二级缓存都会被清空，默认值：false。
              </td>
            </tr>
            
<tr class="b">
              
<td><tt>useCache</tt></td>
              
<td>将其设置为 true，将会导致本条语句的结果被二级缓存，默认值：对 select 元素为 true。
              </td>
            </tr>
            
<tr class="a">
              
<td><tt>timeout</tt></td>
              
<td>这个设置是在抛出异常之前，驱动程序等待数据库返回请求结果的秒数。默认值为 unset（依赖驱动）。
              </td>
            </tr>
            
<tr class="b">
              
<td><tt>fetchSize</tt></td>
              
<td>这是尝试影响驱动程序每次批量返回的结果行数和这个设置值相等。默认值为 unset（依赖驱动）。
              </td>
            </tr>
            
<tr class="a">
              
<td><tt>statementType</tt></td>
              
<td>STATEMENT，PREPARED 或 CALLABLE 的一个。这会让 MyBatis 分别使用 Statement，PreparedStatement 或 CallableStatement，默认值：PREPARED。
              </td>
            </tr>
            
<tr class="b">
              
<td><tt>resultSetType</tt></td>
              
<td>FORWARD_ONLY，SCROLL_SENSITIVE 或 SCROLL_INSENSITIVE 中的一个，默认值为 unset （依赖驱动）。
              </td>
            </tr>
            
<tr class="a">
              
<td><tt>databaseId</tt></td>
              
<td>如果配置了 databaseIdProvider，MyBatis 会加载所有的不带 databaseId 或匹配当前 databaseId 的语句；如果带或者不带的语句都有，则不带的会被忽略。
              </td>
            </tr>
            
<tr class="b">
              
<td><tt>resultOrdered</tt></td>
              
<td>这个设置仅针对嵌套结果 select 语句适用：如果为 true，就是假设包含了嵌套结果集或是分组了，这样的话当返回一个主结果行的时候，就不会发生有对前面结果集的引用的情况。这就使得在获取嵌套的结果集的时候不至于导致内存不够用。默认值：<tt>false</tt>。
              </td>
            </tr>
            
<tr class="a">
              
<td><tt>resultSets</tt></td>
              
<td>这个设置仅对多结果集的情况适用，它将列出语句执行后返回的结果集并每个结果集给一个名称，名称是逗号分隔的。
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <a name="insert_update_and_delete"></a>
<div class="section" id="insert_update_and_delete">
<h3><a name="insert_update__delete"></a>insert, update 和 delete</h3>
        
<p>
        数据变更语句 insert，update 和 delete 的实现非常接近：
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;insert</span><span class="pln">
  </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"insertAuthor"</span><span class="pln">
  </span><span class="atn">parameterType</span><span class="pun">=</span><span class="atv">"domain.blog.Author"</span><span class="pln">
  </span><span class="atn">flushCache</span><span class="pun">=</span><span class="atv">"true"</span><span class="pln">
  </span><span class="atn">statementType</span><span class="pun">=</span><span class="atv">"PREPARED"</span><span class="pln">
  </span><span class="atn">keyProperty</span><span class="pun">=</span><span class="atv">""</span><span class="pln">
  </span><span class="atn">keyColumn</span><span class="pun">=</span><span class="atv">""</span><span class="pln">
  </span><span class="atn">useGeneratedKeys</span><span class="pun">=</span><span class="atv">""</span><span class="pln">
  </span><span class="atn">timeout</span><span class="pun">=</span><span class="atv">"20"</span><span class="tag">&gt;</span><span class="pln">

</span><span class="tag">&lt;update</span><span class="pln">
  </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"updateAuthor"</span><span class="pln">
  </span><span class="atn">parameterType</span><span class="pun">=</span><span class="atv">"domain.blog.Author"</span><span class="pln">
  </span><span class="atn">flushCache</span><span class="pun">=</span><span class="atv">"true"</span><span class="pln">
  </span><span class="atn">statementType</span><span class="pun">=</span><span class="atv">"PREPARED"</span><span class="pln">
  </span><span class="atn">timeout</span><span class="pun">=</span><span class="atv">"20"</span><span class="tag">&gt;</span><span class="pln">

</span><span class="tag">&lt;delete</span><span class="pln">
  </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"deleteAuthor"</span><span class="pln">
  </span><span class="atn">parameterType</span><span class="pun">=</span><span class="atv">"domain.blog.Author"</span><span class="pln">
  </span><span class="atn">flushCache</span><span class="pun">=</span><span class="atv">"true"</span><span class="pln">
  </span><span class="atn">statementType</span><span class="pun">=</span><span class="atv">"PREPARED"</span><span class="pln">
  </span><span class="atn">timeout</span><span class="pun">=</span><span class="atv">"20"</span><span class="tag">&gt;</span></pre></div>

        
<table border="0" class="table table-striped"><caption>Insert, Update &amp;#x548c; Delete &amp;#x7684;&amp;#x5c5e;&amp;#x6027;</caption>
          
          <thead>
            
<tr class="a">
              
<th>属性</th>
              
<th>描述</th>
            </tr>
          </thead>
          <tbody>
            
<tr class="b">
              
<td><tt>id</tt></td>
              
<td>命名空间中的唯一标识符，可被用来代表这条语句。</td>
            </tr>
            
<tr class="a">
              
<td><tt>parameterType</tt></td>
              
<td>将要传入语句的参数的完全限定类名或别名。这个属性是可选的，因为 MyBatis 可以通过 TypeHandler 推断出具体传入语句的参数，默认值为 unset。
              </td>
            </tr>
            
<tr class="b">
              
<td>
                <tt><s>parameterMap</s></tt>
              </td>
              
<td>
                <s>这是引用外部 parameterMap 的已经被废弃的方法。使用内联参数映射和 parameterType 属性。
                </s>
              </td>
            </tr>
            
<tr class="a">
              
<td><tt>flushCache</tt></td>
              
<td>将其设置为 true，任何时候只要语句被调用，都会导致本地缓存和二级缓存都会被清空，默认值：true（对应插入、更新和删除语句）。
              </td>
            </tr>
            
<tr class="b">
              
<td><tt>timeout</tt></td>
              
<td>这个设置是在抛出异常之前，驱动程序等待数据库返回请求结果的秒数。默认值为 unset（依赖驱动）。
              </td>
            </tr>
            
<tr class="a">
              
<td><tt>statementType</tt></td>
              
<td>STATEMENT，PREPARED 或 CALLABLE 的一个。这会让 MyBatis 分别使用 Statement，PreparedStatement 或 CallableStatement，默认值：PREPARED。
              </td>
            </tr>
            
<tr class="b">
              
<td><tt>useGeneratedKeys</tt></td>
              
<td>（仅对 insert 和 update 有用）这会令 MyBatis 使用 JDBC 的 getGeneratedKeys 方法来取出由数据库内部生成的主键（比如：像 MySQL 和 SQL Server 这样的关系数据库管理系统的自动递增字段），默认值：false。
              </td>
            </tr>
            
<tr class="a">
              
<td><tt>keyProperty</tt></td>
              
<td>（仅对 insert 和 update 有用）唯一标记一个属性，MyBatis 会通过 getGeneratedKeys 的返回值或者通过 insert 语句的 selectKey 子元素设置它的键值，默认：<tt>unset</tt>。如果希望得到多个生成的列，也可以是逗号分隔的属性名称列表。
              </td>
            </tr>
            
<tr class="b">
              
<td><tt>keyColumn</tt></td>
              
<td>（仅对 insert 和 update 有用）通过生成的键值设置表中的列名，这个设置仅在某些数据库（像 PostgreSQL）是必须的，当主键列不是表中的第一列的时候需要设置。如果希望得到多个生成的列，也可以是逗号分隔的属性名称列表。
              </td>
            </tr>
            
<tr class="a">
              
<td><tt>databaseId</tt></td>
              
<td>如果配置了 databaseIdProvider，MyBatis 会加载所有的不带 databaseId 或匹配当前 databaseId 的语句；如果带或者不带的语句都有，则不带的会被忽略。
              </td>
            </tr>
          </tbody>
        </table>

        
<p>下面就是 insert，update 和 delete 语句的示例：</p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;insert</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"insertAuthor"</span><span class="tag">&gt;</span><span class="pln">
  insert into Author (id,username,password,email,bio)
  values (#{id},#{username},#{password},#{email},#{bio})
</span><span class="tag">&lt;/insert&gt;</span><span class="pln">

</span><span class="tag">&lt;update</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"updateAuthor"</span><span class="tag">&gt;</span><span class="pln">
  update Author set
    username = #{username},
    password = #{password},
    email = #{email},
    bio = #{bio}
  where id = #{id}
</span><span class="tag">&lt;/update&gt;</span><span class="pln">

</span><span class="tag">&lt;delete</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"deleteAuthor"</span><span class="tag">&gt;</span><span class="pln">
  delete from Author where id = #{id}
</span><span class="tag">&lt;/delete&gt;</span></pre></div>

        
<p>如前所述，插入语句的配置规则更加丰富，在插入语句里面有一些额外的属性和子元素用来处理主键的生成，而且有多种生成方式。</p>

        
<p>首先，如果你的数据库支持自动生成主键的字段（比如 MySQL 和 SQL Server），那么你可以设置 useGeneratedKeys=”true”，然后再把 keyProperty 设置到目标属性上就OK了。例如，如果上面的 Author 表已经对 id 使用了自动生成的列类型，那么语句可以修改为:</p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;insert</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"insertAuthor"</span><span class="pln"> </span><span class="atn">useGeneratedKeys</span><span class="pun">=</span><span class="atv">"true"</span><span class="pln">
    </span><span class="atn">keyProperty</span><span class="pun">=</span><span class="atv">"id"</span><span class="tag">&gt;</span><span class="pln">
  insert into Author (username,password,email,bio)
  values (#{username},#{password},#{email},#{bio})
</span><span class="tag">&lt;/insert&gt;</span></pre></div>

        
<p>
          If your database also supports multi-row insert, you can pass a list or an array of <tt>Author</tt>s and retrieve the auto-generated keys.
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;insert</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"insertAuthor"</span><span class="pln"> </span><span class="atn">useGeneratedKeys</span><span class="pun">=</span><span class="atv">"true"</span><span class="pln">
    </span><span class="atn">keyProperty</span><span class="pun">=</span><span class="atv">"id"</span><span class="tag">&gt;</span><span class="pln">
  insert into Author (username, password, email, bio) values
  </span><span class="tag">&lt;foreach</span><span class="pln"> </span><span class="atn">item</span><span class="pun">=</span><span class="atv">"item"</span><span class="pln"> </span><span class="atn">collection</span><span class="pun">=</span><span class="atv">"list"</span><span class="pln"> </span><span class="atn">separator</span><span class="pun">=</span><span class="atv">","</span><span class="tag">&gt;</span><span class="pln">
    (#{item.username}, #{item.password}, #{item.email}, #{item.bio})
  </span><span class="tag">&lt;/foreach&gt;</span><span class="pln">
</span><span class="tag">&lt;/insert&gt;</span></pre></div>

        
<p>对于不支持自动生成类型的数据库或可能不支持自动生成主键 JDBC 驱动来说，MyBatis 有另外一种方法来生成主键。
        </p>

        
<p>这里有一个简单（甚至很傻）的示例，它可以生成一个随机 ID（你最好不要这么做，但这里展示了 MyBatis 处理问题的灵活性及其所关心的广度）：
        </p>
        
        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;insert</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"insertAuthor"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;selectKey</span><span class="pln"> </span><span class="atn">keyProperty</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">resultType</span><span class="pun">=</span><span class="atv">"int"</span><span class="pln"> </span><span class="atn">order</span><span class="pun">=</span><span class="atv">"BEFORE"</span><span class="tag">&gt;</span><span class="pln">
    select CAST(RANDOM()*1000000 as INTEGER) a from SYSIBM.SYSDUMMY1
  </span><span class="tag">&lt;/selectKey&gt;</span><span class="pln">
  insert into Author
    (id, username, password, email,bio, favourite_section)
  values
    (#{id}, #{username}, #{password}, #{email}, #{bio}, #{favouriteSection,jdbcType=VARCHAR})
</span><span class="tag">&lt;/insert&gt;</span></pre></div>
        
<p>在上面的示例中，selectKey 元素将会首先运行，Author 的 id 会被设置，然后插入语句会被调用。这给你了一个和数据库中来处理自动生成的主键类似的行为，避免了使 Java 代码变得复杂。
        </p>
        
<p>selectKey 元素描述如下：
        </p>
        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;selectKey</span><span class="pln">
  </span><span class="atn">keyProperty</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln">
  </span><span class="atn">resultType</span><span class="pun">=</span><span class="atv">"int"</span><span class="pln">
  </span><span class="atn">order</span><span class="pun">=</span><span class="atv">"BEFORE"</span><span class="pln">
  </span><span class="atn">statementType</span><span class="pun">=</span><span class="atv">"PREPARED"</span><span class="tag">&gt;</span></pre></div>

        
<table border="0" class="table table-striped"><caption>selectKey &amp;#x7684;&amp;#x5c5e;&amp;#x6027;</caption>
          
          <thead>
            
<tr class="a">
              
<th>属性</th>
              
<th>描述</th>
            </tr>
          </thead>
          <tbody>
            
<tr class="b">
              
<td><tt>keyProperty</tt></td>
              
<td>selectKey 语句结果应该被设置的目标属性。如果希望得到多个生成的列，也可以是逗号分隔的属性名称列表。
              </td>
            </tr>
            
<tr class="a">
              
<td><tt>keyColumn</tt></td>
              
<td>匹配属性的返回结果集中的列名称。如果希望得到多个生成的列，也可以是逗号分隔的属性名称列表。
              </td>
            </tr>
            
<tr class="b">
              
<td><tt>resultType</tt></td>
              
<td>结果的类型。MyBatis 通常可以推算出来，但是为了更加确定写上也不会有什么问题。MyBatis 允许任何简单类型用作主键的类型，包括字符串。如果希望作用于多个生成的列，则可以使用一个包含期望属性的 Object 或一个 Map。
              </td>
            </tr>
            
<tr class="a">
              
<td><tt>order</tt></td>
              
<td>这可以被设置为 BEFORE 或 AFTER。如果设置为 BEFORE，那么它会首先选择主键，设置 keyProperty 然后执行插入语句。如果设置为 AFTER，那么先执行插入语句，然后是 selectKey 元素 - 这和像 Oracle 的数据库相似，在插入语句内部可能有嵌入索引调用。
              </td>
            </tr>
            
<tr class="b">
              
<td><tt>statementType</tt></td>
              
<td>与前面相同，MyBatis 支持 STATEMENT，PREPARED 和 CALLABLE 语句的映射类型，分别代表 PreparedStatement 和 CallableStatement 类型。
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      
<div class="section">
<h3><a name="sql"></a>sql</h3>
        
<p>这个元素可以被用来定义可重用的 SQL 代码段，可以包含在其他语句中。它可以被静态地(在加载参数) 参数化. 不同的属性值通过包含的实例变化. 比如：
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;sql</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"userColumns"</span><span class="tag">&gt;</span><span class="pln"> ${alias}.id,${alias}.username,${alias}.password </span><span class="tag">&lt;/sql&gt;</span></pre></div>

        
<p>这个 SQL 片段可以被包含在其他语句中，例如：
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;select</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"selectUsers"</span><span class="pln"> </span><span class="atn">resultType</span><span class="pun">=</span><span class="atv">"map"</span><span class="tag">&gt;</span><span class="pln">
  select
    </span><span class="tag">&lt;include</span><span class="pln"> </span><span class="atn">refid</span><span class="pun">=</span><span class="atv">"userColumns"</span><span class="tag">&gt;&lt;property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"alias"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"t1"</span><span class="tag">/&gt;&lt;/include&gt;</span><span class="pln">,
    </span><span class="tag">&lt;include</span><span class="pln"> </span><span class="atn">refid</span><span class="pun">=</span><span class="atv">"userColumns"</span><span class="tag">&gt;&lt;property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"alias"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"t2"</span><span class="tag">/&gt;&lt;/include&gt;</span><span class="pln">
  from some_table t1
    cross join some_table t2
</span><span class="tag">&lt;/select&gt;</span></pre></div>

        
<p>
          属性值可以用于包含的refid属性或者包含的字句里面的属性值，例如：
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;sql</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"sometable"</span><span class="tag">&gt;</span><span class="pln">
  ${prefix}Table
</span><span class="tag">&lt;/sql&gt;</span><span class="pln">

</span><span class="tag">&lt;sql</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"someinclude"</span><span class="tag">&gt;</span><span class="pln">
  from
    </span><span class="tag">&lt;include</span><span class="pln"> </span><span class="atn">refid</span><span class="pun">=</span><span class="atv">"${include_target}"</span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;/sql&gt;</span><span class="pln">

</span><span class="tag">&lt;select</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"select"</span><span class="pln"> </span><span class="atn">resultType</span><span class="pun">=</span><span class="atv">"map"</span><span class="tag">&gt;</span><span class="pln">
  select
    field1, field2, field3
  </span><span class="tag">&lt;include</span><span class="pln"> </span><span class="atn">refid</span><span class="pun">=</span><span class="atv">"someinclude"</span><span class="tag">&gt;</span><span class="pln">
    </span><span class="tag">&lt;property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"prefix"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"Some"</span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"include_target"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"sometable"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;/include&gt;</span><span class="pln">
</span><span class="tag">&lt;/select&gt;</span></pre></div>
      </div>

      <a name="Parameters"></a>
<div class="section" id="Parameters">
<h3><a name="aParameters"></a>参数（Parameters）</h3>
        
<p>前面的所有语句中你所见到的都是简单参数的例子，实际上参数是 MyBatis 非常强大的元素，对于简单的做法，大概 90% 的情况参数都很少，比如：
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;select</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"selectUsers"</span><span class="pln"> </span><span class="atn">resultType</span><span class="pun">=</span><span class="atv">"User"</span><span class="tag">&gt;</span><span class="pln">
  select id, username, password
  from users
  where id = #{id}
</span><span class="tag">&lt;/select&gt;</span></pre></div>

        
<p>上面的这个示例说明了一个非常简单的命名参数映射。参数类型被设置为 <tt>int</tt>，这样这个参数就可以被设置成任何内容。原生的类型或简单数据类型（比如整型和字符串）因为没有相关属性，它会完全用参数值来替代。然而，如果传入一个复杂的对象，行为就会有一点不同了。比如：
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;insert</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"insertUser"</span><span class="pln"> </span><span class="atn">parameterType</span><span class="pun">=</span><span class="atv">"User"</span><span class="tag">&gt;</span><span class="pln">
  insert into users (id, username, password)
  values (#{id}, #{username}, #{password})
</span><span class="tag">&lt;/insert&gt;</span></pre></div>

        
<p>如果 User 类型的参数对象传递到了语句中，id、username 和 password 属性将会被查找，然后将它们的值传入预处理语句的参数中。
        </p>

        
<p>这点对于向语句中传参是比较好的而且又简单，不过参数映射的功能远不止于此。
        </p>

        
<p>首先，像 MyBatis 的其他部分一样，参数也可以指定一个特殊的数据类型。
        </p>

        
<div class="source"><pre class="prettyprint"><span class="com">#{property,javaType=int,jdbcType=NUMERIC}</span></pre></div>

        
<p>像 MyBatis 的剩余部分一样，javaType 通常可以从参数对象中来去确定，前提是只要对象不是一个 HashMap。那么 javaType 应该被确定来保证使用正确类型处理器。
        </p>

        
<p><span class="label important">NOTE</span> 如果 null 被当作值来传递，对于所有可能为空的列，JDBC Type 是需要的。你可以自己通过阅读预处理语句的 setNull() 方法的 JavaDocs 文档来研究这种情况。
        </p>

        
<p>为了以后定制类型处理方式，你也可以指定一个特殊的类型处理器类（或别名），比如：
        </p>

        
<div class="source"><pre class="prettyprint"><span class="com">#{age,javaType=int,jdbcType=NUMERIC,typeHandler=MyTypeHandler}</span></pre></div>

        
<p>尽管看起来配置变得越来越繁琐，但实际上是很少去设置它们。
        </p>

        
<p>对于数值类型，还有一个小数保留位数的设置，来确定小数点后保留的位数。
        </p>

        
<div class="source"><pre class="prettyprint"><span class="com">#{height,javaType=double,jdbcType=NUMERIC,numericScale=2}</span></pre></div>

        
<p>最后，mode 属性允许你指定 IN，OUT 或 INOUT 参数。如果参数为 OUT 或 INOUT，参数对象属性的真实值将会被改变，就像你在获取输出参数时所期望的那样。如果 mode 为 OUT（或 INOUT），而且 jdbcType 为 CURSOR(也就是 Oracle 的 REFCURSOR)，你必须指定一个 resultMap 来映射结果集到参数类型。要注意这里的 javaType 属性是可选的，如果左边的空白是 jdbcType 的 CURSOR 类型，它会自动地被设置为结果集。
        </p>

        
<div class="source"><pre class="prettyprint"><span class="com">#{department, mode=OUT, jdbcType=CURSOR, javaType=ResultSet, resultMap=departmentResultMap}</span></pre></div>

        
<p>MyBatis 也支持很多高级的数据类型，比如结构体，但是当注册 out 参数时你必须告诉它语句类型名称。比如（再次提示，在实际中要像这样不能换行）：
        </p>

        
<div class="source"><pre class="prettyprint"><span class="com">#{middleInitial, mode=OUT, jdbcType=STRUCT, jdbcTypeName=MY_TYPE, resultMap=departmentResultMap}</span></pre></div>

        
<p>尽管所有这些强大的选项很多时候你只简单指定属性名，其他的事情 MyBatis 会自己去推断，最多你需要为可能为空的列名指定 <tt>jdbcType</tt>。
        </p>

        
<div class="source"><pre class="prettyprint"><span class="com">#{firstName}</span><span class="pln">
</span><span class="com">#{middleInitial,jdbcType=VARCHAR}</span><span class="pln">
</span><span class="com">#{lastName}</span></pre></div>

        
<div class="section">
<h4><a name="a"></a>
          字符串替换
        </h4>

        
<p>默认情况下,使用#{}格式的语法会导致 MyBatis 创建预处理语句属性并安全地设置值（比如?）。这样做更安全，更迅速，通常也是首选做法，不过有时你只是想直接在 SQL 语句中插入一个不改变的字符串。比如，像 ORDER BY，你可以这样来使用：
        </p>

        
<div class="source"><pre class="prettyprint"><span class="pln">ORDER BY $</span><span class="pun">{</span><span class="pln">columnName</span><span class="pun">}</span></pre></div>

        
<p>这里 MyBatis 不会修改或转义字符串。
        </p>

        
<p>
          <span class="label important">NOTE</span> 以这种方式接受从用户输出的内容并提供给语句中不变的字符串是不安全的，会导致潜在的 SQL 注入攻击，因此要么不允许用户输入这些字段，要么自行转义并检验。
        </p>
      </div></div>

      <a name="Result_Maps"></a>
<div class="section" id="Result_Maps">
<h3><a name="Result_Maps"></a>Result Maps</h3>
        
<p>
resultMap 元素是 MyBatis 中最重要最强大的元素。它就是让你远离 90%的需要从结果
集中取出数据的 JDBC 代码的那个东西,
而且在一些情形下允许你做一些 JDBC 不支持的事
情。
事实上,
编写相似于对复杂语句联合映射这些等同的代码,
也许可以跨过上千行的代码。
ResultMap 的设计就是简单语句不需要明确的结果映射,而很多复杂语句确实需要描述它们
的关系。
        </p>

        
<p>
你已经看到简单映射语句的示例了,但没有明确的 resultMap。比如:
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;select</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"selectUsers"</span><span class="pln"> </span><span class="atn">resultType</span><span class="pun">=</span><span class="atv">"map"</span><span class="tag">&gt;</span><span class="pln">
  select id, username, hashedPassword
  from some_table
  where id = #{id}
</span><span class="tag">&lt;/select&gt;</span></pre></div>

        
<p>
这样一个语句简单作用于所有列被自动映射到 HashMap 的键上,这由 resultType 属性
指定。这在很多情况下是有用的,但是 HashMap 不能很好描述一个领域模型。那样你的应
用程序将会使用 JavaBeans 或 POJOs(Plain Old Java Objects,普通 Java 对象)来作为领域
模型。MyBatis 对两者都支持。看看下面这个 JavaBean:
        </p>
        
<div class="source"><pre class="prettyprint"><span class="kwd">package</span><span class="pln"> com</span><span class="pun">.</span><span class="pln">someapp</span><span class="pun">.</span><span class="pln">model</span><span class="pun">;</span><span class="pln">
</span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">User</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="kwd">private</span><span class="pln"> </span><span class="kwd">int</span><span class="pln"> id</span><span class="pun">;</span><span class="pln">
  </span><span class="kwd">private</span><span class="pln"> </span><span class="typ">String</span><span class="pln"> username</span><span class="pun">;</span><span class="pln">
  </span><span class="kwd">private</span><span class="pln"> </span><span class="typ">String</span><span class="pln"> hashedPassword</span><span class="pun">;</span><span class="pln">
  
  </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">int</span><span class="pln"> getId</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">return</span><span class="pln"> id</span><span class="pun">;</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
  </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> setId</span><span class="pun">(</span><span class="kwd">int</span><span class="pln"> id</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">id </span><span class="pun">=</span><span class="pln"> id</span><span class="pun">;</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
  </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">String</span><span class="pln"> getUsername</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">return</span><span class="pln"> username</span><span class="pun">;</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
  </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> setUsername</span><span class="pun">(</span><span class="typ">String</span><span class="pln"> username</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">username </span><span class="pun">=</span><span class="pln"> username</span><span class="pun">;</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
  </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">String</span><span class="pln"> getHashedPassword</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">return</span><span class="pln"> hashedPassword</span><span class="pun">;</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
  </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> setHashedPassword</span><span class="pun">(</span><span class="typ">String</span><span class="pln"> hashedPassword</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
    </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">hashedPassword </span><span class="pun">=</span><span class="pln"> hashedPassword</span><span class="pun">;</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
</span><span class="pun">}</span></pre></div>

        
<p>
基于 JavaBean 的规范,上面这个类有 3 个属性:id,username 和 hashedPassword。这些
在 select 语句中会精确匹配到列名。
        </p>

        
<p>
这样的一个 JavaBean 可以被映射到结果集,就像映射到 HashMap 一样简单。
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;select</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"selectUsers"</span><span class="pln"> </span><span class="atn">resultType</span><span class="pun">=</span><span class="atv">"com.someapp.model.User"</span><span class="tag">&gt;</span><span class="pln">
  select id, username, hashedPassword
  from some_table
  where id = #{id}
</span><span class="tag">&lt;/select&gt;</span></pre></div>

        
<p>
要记住类型别名是你的伙伴。使用它们你可以不用输入类的全路径。比如:
        </p>

        
<div class="source"><pre class="prettyprint"><span class="com">&lt;!-- In mybatis-config.xml file --&gt;</span><span class="pln">
</span><span class="tag">&lt;typeAlias</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"com.someapp.model.User"</span><span class="pln"> </span><span class="atn">alias</span><span class="pun">=</span><span class="atv">"User"</span><span class="tag">/&gt;</span><span class="pln">

</span><span class="com">&lt;!-- In SQL Mapping XML file --&gt;</span><span class="pln">
</span><span class="tag">&lt;select</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"selectUsers"</span><span class="pln"> </span><span class="atn">resultType</span><span class="pun">=</span><span class="atv">"User"</span><span class="tag">&gt;</span><span class="pln">
  select id, username, hashedPassword
  from some_table
  where id = #{id}
</span><span class="tag">&lt;/select&gt;</span></pre></div>

        
<p>
这些情况下,MyBatis 会在幕后自动创建一个 ResultMap,基于属性名来映射列到
JavaBean 的属性上。如果列名没有精确匹配,你可以在列名上使用 select 字句的别名(一个
基本的 SQL 特性)来匹配标签。比如:
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;select</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"selectUsers"</span><span class="pln"> </span><span class="atn">resultType</span><span class="pun">=</span><span class="atv">"User"</span><span class="tag">&gt;</span><span class="pln">
  select
    user_id             as "id",
    user_name           as "userName",
    hashed_password     as "hashedPassword"
  from some_table
  where id = #{id}
</span><span class="tag">&lt;/select&gt;</span></pre></div>

        
<p>
ResultMap 最优秀的地方你已经了解了很多了,但是你还没有真正的看到一个。这些简
单的示例不需要比你看到的更多东西。
只是出于示例的原因,
让我们来看看最后一个示例中
外部的 resultMap 是什么样子的,这也是解决列名不匹配的另外一种方式。
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;resultMap</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"userResultMap"</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"User"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;id</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"user_id"</span><span class="pln"> </span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"username"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"user_name"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"password"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"hashed_password"</span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;/resultMap&gt;</span></pre></div>

        
<p>
引用它的语句使用 resultMap 属性就行了(注意我们去掉了 resultType 属性)。比如:
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;select</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"selectUsers"</span><span class="pln"> </span><span class="atn">resultMap</span><span class="pun">=</span><span class="atv">"userResultMap"</span><span class="tag">&gt;</span><span class="pln">
  select user_id, user_name, hashed_password
  from some_table
  where id = #{id}
</span><span class="tag">&lt;/select&gt;</span></pre></div>

        
<p>
如果世界总是这么简单就好了。
        </p>

	      
<div class="section">
<h4><a name="a"></a>高级结果映射</h4>

        
<p>
MyBatis 创建的一个想法:数据库不用永远是你想要的或需要它们是什么样的。而我们
最喜欢的数据库最好是第三范式或 BCNF 模式,但它们有时不是。如果可能有一个单独的
数据库映射,所有应用程序都可以使用它,这是非常好的,但有时也不是。结果映射就是
MyBatis 提供处理这个问题的答案。
        </p>

        
<p>
比如,我们如何映射下面这个语句?
        </p>

        
<div class="source"><pre class="prettyprint"><span class="com">&lt;!-- Very Complex Statement --&gt;</span><span class="pln">
</span><span class="tag">&lt;select</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"selectBlogDetails"</span><span class="pln"> </span><span class="atn">resultMap</span><span class="pun">=</span><span class="atv">"detailedBlogResultMap"</span><span class="tag">&gt;</span><span class="pln">
  select
       B.id as blog_id,
       B.title as blog_title,
       B.author_id as blog_author_id,
       A.id as author_id,
       A.username as author_username,
       A.password as author_password,
       A.email as author_email,
       A.bio as author_bio,
       A.favourite_section as author_favourite_section,
       P.id as post_id,
       P.blog_id as post_blog_id,
       P.author_id as post_author_id,
       P.created_on as post_created_on,
       P.section as post_section,
       P.subject as post_subject,
       P.draft as draft,
       P.body as post_body,
       C.id as comment_id,
       C.post_id as comment_post_id,
       C.name as comment_name,
       C.comment as comment_text,
       T.id as tag_id,
       T.name as tag_name
  from Blog B
       left outer join Author A on B.author_id = A.id
       left outer join Post P on B.id = P.blog_id
       left outer join Comment C on P.id = C.post_id
       left outer join Post_Tag PT on PT.post_id = P.id
       left outer join Tag T on PT.tag_id = T.id
  where B.id = #{id}
</span><span class="tag">&lt;/select&gt;</span></pre></div>

        
<p>
你可能想把它映射到一个智能的对象模型,包含一个作者写的博客,有很多的博文,每
篇博文有零条或多条的评论和标签。
下面是一个完整的复杂结果映射例子
(假设作者,
博客,
博文,
评论和标签都是类型的别名) 我们来看看,
。
但是不用紧张,
我们会一步一步来说明。
当天最初它看起来令人生畏,但实际上非常简单。
        </p>

        
<div class="source"><pre class="prettyprint"><span class="com">&lt;!-- Very Complex Result Map --&gt;</span><span class="pln">
</span><span class="tag">&lt;resultMap</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"detailedBlogResultMap"</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"Blog"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;constructor&gt;</span><span class="pln">
    </span><span class="tag">&lt;idArg</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"blog_id"</span><span class="pln"> </span><span class="atn">javaType</span><span class="pun">=</span><span class="atv">"int"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;/constructor&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"title"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"blog_title"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;association</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"author"</span><span class="pln"> </span><span class="atn">javaType</span><span class="pun">=</span><span class="atv">"Author"</span><span class="tag">&gt;</span><span class="pln">
    </span><span class="tag">&lt;id</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_id"</span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"username"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_username"</span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"password"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_password"</span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"email"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_email"</span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"bio"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_bio"</span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"favouriteSection"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_favourite_section"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;/association&gt;</span><span class="pln">
  </span><span class="tag">&lt;collection</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"posts"</span><span class="pln"> </span><span class="atn">ofType</span><span class="pun">=</span><span class="atv">"Post"</span><span class="tag">&gt;</span><span class="pln">
    </span><span class="tag">&lt;id</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"post_id"</span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"subject"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"post_subject"</span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;association</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"author"</span><span class="pln"> </span><span class="atn">javaType</span><span class="pun">=</span><span class="atv">"Author"</span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;collection</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"comments"</span><span class="pln"> </span><span class="atn">ofType</span><span class="pun">=</span><span class="atv">"Comment"</span><span class="tag">&gt;</span><span class="pln">
      </span><span class="tag">&lt;id</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"comment_id"</span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;/collection&gt;</span><span class="pln">
    </span><span class="tag">&lt;collection</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"tags"</span><span class="pln"> </span><span class="atn">ofType</span><span class="pun">=</span><span class="atv">"Tag"</span><span class="pln"> </span><span class="tag">&gt;</span><span class="pln">
      </span><span class="tag">&lt;id</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"tag_id"</span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;/collection&gt;</span><span class="pln">
    </span><span class="tag">&lt;discriminator</span><span class="pln"> </span><span class="atn">javaType</span><span class="pun">=</span><span class="atv">"int"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"draft"</span><span class="tag">&gt;</span><span class="pln">
      </span><span class="tag">&lt;case</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"1"</span><span class="pln"> </span><span class="atn">resultType</span><span class="pun">=</span><span class="atv">"DraftPost"</span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;/discriminator&gt;</span><span class="pln">
  </span><span class="tag">&lt;/collection&gt;</span><span class="pln">
</span><span class="tag">&lt;/resultMap&gt;</span></pre></div>

        
<p>
resultMap 元素有很多子元素和一个值得讨论的结构。
下面是 resultMap 元素的概念视图
        </p>

        </div>
<div class="section">
<h4><a name="resultMap"></a>resultMap</h4>
        
<ul>
          
<li>
            <tt>constructor</tt> - 类在实例化时,用来注入结果到构造方法中
            
<ul>
              
<li><tt>idArg</tt> - ID 参数;标记结果作为 ID 可以帮助提高整体效能</li>
              
<li><tt>arg</tt> - 注入到构造方法的一个普通结果</li>
            </ul>
          </li>
          
<li><tt>id</tt> – 一个 ID 结果;标记结果作为 ID 可以帮助提高整体效能</li>
          
<li><tt>result</tt> – 注入到字段或 JavaBean 属性的普通结果</li>
          
<li>
            <tt>association</tt> – 一个复杂的类型关联;许多结果将包成这种类型
            
<ul>
              
<li>嵌入结果映射 – 结果映射自身的关联,或者参考一个
              </li>
            </ul>
          </li>
          
<li>
            <tt>collection</tt> – 复杂类型的集
            
<ul>
              
<li>嵌入结果映射 – 结果映射自身的集,或者参考一个</li>
            </ul>
          </li>
          
<li>
            <tt>discriminator</tt> – 使用结果值来决定使用哪个结果映射
            
<ul>
              
<li>
                <tt>case</tt> – 基于某些值的结果映射
                
<ul>
                  
<li>嵌入结果映射 – 这种情形结果也映射它本身,因此可以包含很多相
                      同的元素,或者它可以参照一个外部的结果映射。
                  </li>
                </ul>
              </li>
            </ul>
          </li>
        </ul>

        
<table border="0" class="table table-striped"><caption>ResultMap Attributes</caption>
          
          <thead>
            
<tr class="a">
              
<th>Attribute</th>
              
<th>Description</th>
            </tr>
          </thead>
          <tbody>
            
<tr class="b">
              
<td><tt>id</tt></td>
              
<td>A unique identifier in this namespace that can be used to reference this result map.</td>
            </tr>
            
<tr class="a">
              
<td><tt>type</tt></td>
              
<td>A fully qualified Java class name, or a type alias (see the table above for the list of built-in type aliases). 
              </td>
            </tr>
            
<tr class="b">
              
<td><tt>autoMapping</tt></td>
              
<td>If present, MyBatis will enable or disable the automapping for this ResultMap. 
                This attribute overrides the global autoMappingBehavior. Default: unset. 
              </td>
            </tr>
          </tbody>
        </table>

        
<p>
          <span class="label important">最佳实践</span> 通常逐步建立结果映射。单元测试的真正帮助在这里。如果你尝试创建
一次创建一个向上面示例那样的巨大的结果映射,
那么可能会有错误而且很难去控制它
来工作。开始简单一些,一步一步的发展。而且要进行单元测试!使用该框架的缺点是
它们有时是黑盒(是否可见源代码)
。你确定你实现想要的行为的最好选择是编写单元
测试。它也可以你帮助得到提交时的错误。
        </p>

        
<p>
下面一部分将详细说明每个元素。
        </p>

        </div>
<div class="section">
<h4><a name="id__result"></a>id &amp; result</h4>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;id</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"post_id"</span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"subject"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"post_subject"</span><span class="tag">/&gt;</span></pre></div>

        
<p>
这些是结果映射最基本内容。id 和 result 都映射一个单独列的值到简单数据类型(字符
串,整型,双精度浮点数,日期等)的单独属性或字段。
        </p>

        
<p>
这两者之间的唯一不同是 id 表示的结果将是当比较对象实例时用到的标识属性。这帮
助来改进整体表现,特别是缓存和嵌入结果映射(也就是联合映射)
。      </p>

        
<p>
每个都有一些属性:
        </p>

        
<table border="0" class="table table-striped"><caption>Id and Result Attributes</caption>
          
          <thead>
            
<tr class="a">
              
<th>属性</th>
              
<th>描述</th>
            </tr>
          </thead>
          <tbody>
            
<tr class="b">
              
<td><tt>property</tt></td>
              
<td>
映射到列结果的字段或属性。如果匹配的是存在的,和给定名称相同
的 JavaBeans 的属性,那么就会使用。否则 MyBatis 将会寻找给定名称
property
的字段。这两种情形你可以使用通常点式的复杂属性导航。比如,你
可以这样映射一些东西:
“username”
,或者映射到一些复杂的东西:
“address.street.number”
。
              </td>
            </tr>
            
<tr class="a">
              
<td><tt>column</tt></td>
              
<td>
从数据库中得到的列名,或者是列名的重命名标签。这也是通常和会
传递给 resultSet.getString(columnName)方法参数中相同的字符串。
              </td>
            </tr>
            
<tr class="b">
              
<td><tt>javaType</tt></td>
              
<td>
一个 Java 类的完全限定名,或一个类型别名(参考上面内建类型别名
的列表)
。如果你映射到一个 JavaBean,MyBatis 通常可以断定类型。
然而,如果你映射到的是 HashMap,那么你应该明确地指定 javaType
来保证所需的行为。
              </td>
            </tr>
            
<tr class="a">
              
<td><tt>jdbcType</tt></td>
              
<td>
在这个表格之后的所支持的 JDBC 类型列表中的类型。JDBC 类型是仅
仅需要对插入,更新和删除操作可能为空的列进行处理。这是 JDBC
jdbcType
的需要,而不是 MyBatis 的。如果你直接使用 JDBC 编程,你需要指定
这个类型-但仅仅对可能为空的值。
              </td>
            </tr>
            
<tr class="b">
              
<td><tt>typeHandler</tt></td>
              
<td>
我们在前面讨论过默认的类型处理器。使用这个属性,你可以覆盖默
认的类型处理器。这个属性值是类的完全限定名或者是一个类型处理
器的实现,或者是类型别名。
              </td>
            </tr>
          </tbody>
        </table>

        </div>
<div class="section">
<h4><a name="a_JDBC_"></a>支持的 JDBC 类型</h4>

        
<p>
为了未来的参考,MyBatis 通过包含的 jdbcType 枚举型,支持下面的 JDBC 类型。
        </p>

        
<table border="0" class="table table-striped">
          
<tbody><tr class="a">
            
<td><tt>BIT</tt></td>
            
<td><tt>FLOAT</tt></td>
            
<td><tt>CHAR</tt></td>
            
<td><tt>TIMESTAMP</tt></td>
            
<td><tt>OTHER</tt></td>
            
<td><tt>UNDEFINED</tt></td>
          </tr>
          
<tr class="b">
            
<td><tt>TINYINT</tt></td>
            
<td><tt>REAL</tt></td>
            
<td><tt>VARCHAR</tt></td>
            
<td><tt>BINARY</tt></td>
            
<td><tt>BLOG</tt></td>
            
<td><tt>NVARCHAR</tt></td>
          </tr>
          
<tr class="a">
            
<td><tt>SMALLINT</tt></td>
            
<td><tt>DOUBLE</tt></td>
            
<td><tt>LONGVARCHAR</tt></td>
            
<td><tt>VARBINARY</tt></td>
            
<td><tt>CLOB</tt></td>
            
<td><tt>NCHAR</tt></td>
          </tr>
          
<tr class="b">
            
<td><tt>INTEGER</tt></td>
            
<td><tt>NUMERIC</tt></td>
            
<td><tt>DATE</tt></td>
            
<td><tt>LONGVARBINARY</tt></td>
            
<td><tt>BOOLEAN</tt></td>
            
<td><tt>NCLOB</tt></td>
          </tr>
          
<tr class="a">
            
<td><tt>BIGINT</tt></td>
            
<td><tt>DECIMAL</tt></td>
            
<td><tt>TIME</tt></td>
            
<td><tt>NULL</tt></td>
            
<td><tt>CURSOR</tt></td>
            
<td><tt>ARRAY</tt></td>
          </tr>
        </tbody></table>

        </div>
<div class="section">
<h4><a name="a"></a>构造方法</h4>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;constructor&gt;</span><span class="pln">
   </span><span class="tag">&lt;idArg</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">javaType</span><span class="pun">=</span><span class="atv">"int"</span><span class="tag">/&gt;</span><span class="pln">
   </span><span class="tag">&lt;arg</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"username"</span><span class="pln"> </span><span class="atn">javaType</span><span class="pun">=</span><span class="atv">"String"</span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;/constructor&gt;</span></pre></div>

        
<p>
对于大多数数据传输对象(Data Transfer Object,DTO)类型,属性可以起作用,而且像
你绝大多数的领域模型,
指令也许是你想使用一成不变的类的地方。
通常包含引用或查询数
据的表很少或基本不变的话对一成不变的类来说是合适的。
构造方法注入允许你在初始化时
为类设置属性的值,而不用暴露出公有方法。MyBatis 也支持私有属性和私有 JavaBeans 属
性来达到这个目的,但是一些人更青睐构造方法注入。构造方法元素支持这个。
        </p>

        
<p>
看看下面这个构造方法:
        </p>

        
<div class="source"><pre class="prettyprint"><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">User</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
   </span><span class="com">//...</span><span class="pln">
   </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">User</span><span class="pun">(</span><span class="kwd">int</span><span class="pln"> id</span><span class="pun">,</span><span class="pln"> </span><span class="typ">String</span><span class="pln"> username</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
     </span><span class="com">//...</span><span class="pln">
  </span><span class="pun">}</span><span class="pln">
</span><span class="com">//...</span><span class="pln">
</span><span class="pun">}</span></pre></div>

        
<p>
为了向这个构造方法中注入结果,MyBatis 需要通过它的参数的类型来标识构造方法。
Java 没有自查(反射)参数名的方法。所以当创建一个构造方法元素时,保证参数是按顺序
排列的,而且数据类型也是确定的。
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;constructor&gt;</span><span class="pln">
   </span><span class="tag">&lt;idArg</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">javaType</span><span class="pun">=</span><span class="atv">"int"</span><span class="tag">/&gt;</span><span class="pln">
   </span><span class="tag">&lt;arg</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"username"</span><span class="pln"> </span><span class="atn">javaType</span><span class="pun">=</span><span class="atv">"String"</span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;/constructor&gt;</span></pre></div>

        
<p>
剩余的属性和规则和固定的 id 和 result 元素是相同的。
        </p>

        
<table border="0" class="table table-striped">
          <thead>
            
<tr class="a">
              
<th>属性</th>
              
<th>描述</th>
            </tr>
          </thead>
          <tbody>
            
<tr class="b">
              
<td><tt>column</tt></td>
              
<td>
来自数据库的类名,或重命名的列标签。这和通常传递给
resultSet.getString(columnName)方法的字符串是相同的。
              </td>
            </tr>
            
<tr class="a">
              
<td><tt>javaType</tt></td>
              
<td>
一个 Java 类的完全限定名,或一个类型别名(参考上面内建类型别名的列表)。
如果你映射到一个 JavaBean,MyBatis 通常可以断定类型。然而,如
果你映射到的是 HashMap,那么你应该明确地指定 javaType 来保证所需的
行为。
              </td>
            </tr>
            
<tr class="b">
              
<td><tt>jdbcType</tt></td>
              
<td>
在这个表格之前的所支持的 JDBC 类型列表中的类型。JDBC 类型是仅仅
需要对插入,
更新和删除操作可能为空的列进行处理。这是 JDBC 的需要,
jdbcType
而不是 MyBatis 的。如果你直接使用 JDBC 编程,你需要指定这个类型-但
仅仅对可能为空的值。
              </td>
            </tr>
            
<tr class="a">
              
<td><tt>typeHandler</tt></td>
              
<td>
我们在前面讨论过默认的类型处理器。使用这个属性,你可以覆盖默认的
类型处理器。
这个属性值是类的完全限定名或者是一个类型处理器的实现,
或者是类型别名。
              </td>
            </tr>
            
<tr class="b">
              
<td><tt>select</tt></td>
              
<td>
                The ID of another mapped statement that will load the complex type required by this
                property mapping. The values retrieved from columns specified in the column attribute
                will be passed to the target select statement as parameters. See the Association element
                for more.
              </td>
            </tr>
            
<tr class="a">
              
<td><tt>resultMap</tt></td>
              
<td>
                This is the ID of a ResultMap that can map the nested results of this argument into an
                appropriate object graph. This is an alternative to using a call to another select
                statement. It allows you to join multiple tables together into a single <tt>ResultSet</tt>. Such
                a <tt>ResultSet</tt> will contain duplicated, repeating groups of data that needs to be
                decomposed and mapped properly to a nested object graph. To facilitate this, MyBatis
                lets you "chain" result maps together, to deal with the nested results. See the
                Association element below for more.
              </td>
            </tr>
          </tbody>
        </table>

        </div>
<div class="section">
<h4><a name="a"></a><tt>关联</tt></h4>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;association</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"author"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"blog_author_id"</span><span class="pln"> </span><span class="atn">javaType</span><span class="pun">=</span><span class="atv">"Author"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;id</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_id"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"username"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_username"</span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;/association&gt;</span></pre></div>

        
<p>
关联元素处理“有一个”类型的关系。比如,在我们的示例中,一个博客有一个用户。
关联映射就工作于这种结果之上。你指定了目标属性,来获取值的列,属性的 java 类型(很
多情况下 MyBatis 可以自己算出来)
,如果需要的话还有 jdbc 类型,如果你想覆盖或获取的
结果值还需要类型控制器。
        </p>

        
<p>
关联中不同的是你需要告诉 MyBatis 如何加载关联。MyBatis 在这方面会有两种不同的
方式:
        </p>

        
<ul>
          
<li>
            嵌套查询:通过执行另外一个 SQL 映射语句来返回预期的复杂类型。
          </li>
          
<li>
            嵌套结果:使用嵌套结果映射来处理重复的联合结果的子集。首先,然让我们来查看这个元素的属性。所有的你都会看到,它和普通的只由 select 和
          </li>
        </ul>

        
<p>
          resultMap 属性的结果映射不同。
        </p>

        
<table border="0" class="table table-striped">
          <thead>
            
<tr class="a">
              
<th>属性</th>
              
<th>描述</th>
            </tr>
          </thead>
          <tbody>
            
<tr class="b">
              
<td><tt>property</tt></td>
              
<td>
映射到列结果的字段或属性。如果匹配的是存在的,和给定名称相同的
property
JavaBeans 的属性,
那么就会使用。
否则 MyBatis 将会寻找给定名称的字段。
这两种情形你可以使用通常点式的复杂属性导航。比如,你可以这样映射
一 些 东 西 :“ username ”, 或 者 映 射 到 一 些 复 杂 的 东 西 :
“address.street.number”
。              </td>
            </tr>
            
<tr class="a">
              
<td><tt>javaType</tt></td>
              
<td>
一个 Java 类的完全限定名,或一个类型别名(参考上面内建类型别名的列
表)
。如果你映射到一个 JavaBean,MyBatis 通常可以断定类型。然而,如
javaType
果你映射到的是 HashMap,那么你应该明确地指定 javaType 来保证所需的
行为。
              </td>
            </tr>
            
<tr class="b">
              
<td><tt>jdbcType</tt></td>
              
<td>
在这个表格之前的所支持的 JDBC 类型列表中的类型。JDBC 类型是仅仅
需要对插入,
更新和删除操作可能为空的列进行处理。这是 JDBC 的需要,
jdbcType
而不是 MyBatis 的。如果你直接使用 JDBC 编程,你需要指定这个类型-但
仅仅对可能为空的值。
              </td>
            </tr>
            
<tr class="a">
              
<td><tt>typeHandler</tt></td>
              
<td>
我们在前面讨论过默认的类型处理器。使用这个属性,你可以覆盖默认的
typeHandler
类型处理器。
这个属性值是类的完全限定名或者是一个类型处理器的实现,
或者是类型别名。
              </td>
            </tr>
          </tbody>
        </table>

        </div>
<div class="section">
<h4><a name="a"></a>关联的嵌套查询</h4>

        
<table border="0" class="table table-striped">
          <thead>
            
<tr class="a">
              
<th>属性</th>
              
<th>描述</th>
            </tr>
          </thead>
          <tbody>
            
<tr class="b">
              
<td><tt>column</tt></td>
              
<td>
来自数据库的类名,或重命名的列标签。这和通常传递给
resultSet.getString(columnName)方法的字符串是相同的。
column
注 意 : 要 处 理 复 合 主 键 , 你 可 以 指 定 多 个 列 名 通 过 column= ”
{prop1=col1,prop2=col2} ” 这种语法来传递给嵌套查询语 句。这会引起
prop1 和 prop2 以参数对象形式来设置给目标嵌套查询语句。
              </td>
            </tr>
            
<tr class="a">
              
<td><tt>select</tt></td>
              
<td>
另外一个映射语句的 ID,可以加载这个属性映射需要的复杂类型。获取的
在列属性中指定的列的值将被传递给目标 select 语句作为参数。表格后面
有一个详细的示例。
select
注 意 : 要 处 理 复 合 主 键 , 你 可 以 指 定 多 个 列 名 通 过 column= ”
{prop1=col1,prop2=col2} ” 这种语法来传递给嵌套查询语 句。这会引起
prop1 和 prop2 以参数对象形式来设置给目标嵌套查询语句。
              </td>
            </tr>
            
<tr class="b">
              
<td><tt>fetchType</tt></td>
              
<td>
                Optional. Valid values are <tt>lazy</tt> and <tt>eager</tt>. If present, it supersedes
                the global configuration parameter <tt>lazyLoadingEnabled</tt> for this mapping.
              </td>
            </tr>
          </tbody>
        </table>

        
<p>
示例:
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;resultMap</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"blogResult"</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"Blog"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;association</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"author"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_id"</span><span class="pln"> </span><span class="atn">javaType</span><span class="pun">=</span><span class="atv">"Author"</span><span class="pln"> </span><span class="atn">select</span><span class="pun">=</span><span class="atv">"selectAuthor"</span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;/resultMap&gt;</span><span class="pln">

</span><span class="tag">&lt;select</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"selectBlog"</span><span class="pln"> </span><span class="atn">resultMap</span><span class="pun">=</span><span class="atv">"blogResult"</span><span class="tag">&gt;</span><span class="pln">
  SELECT * FROM BLOG WHERE ID = #{id}
</span><span class="tag">&lt;/select&gt;</span><span class="pln">

</span><span class="tag">&lt;select</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"selectAuthor"</span><span class="pln"> </span><span class="atn">resultType</span><span class="pun">=</span><span class="atv">"Author"</span><span class="tag">&gt;</span><span class="pln">
  SELECT * FROM AUTHOR WHERE ID = #{id}
</span><span class="tag">&lt;/select&gt;</span></pre></div>

        
<p>
我们有两个查询语句:一个来加载博客,另外一个来加载作者,而且博客的结果映射描
述了“selectAuthor”语句应该被用来加载它的 author 属性。
        </p>

        
<p>
其他所有的属性将会被自动加载,假设它们的列和属性名相匹配。
        </p>

        
<p>
这种方式很简单,
但是对于大型数据集合和列表将不会表现很好。
问题就是我们熟知的
“N+1 查询问题”。概括地讲,N+1 查询问题可以是这样引起的:
        </p>

        
<ul>
          
<li>你执行了一个单独的 SQL 语句来获取结果列表(就是“+1”)。</li>
          
<li>对返回的每条记录,你执行了一个查询语句来为每个加载细节(就是“N”)。
          </li>
        </ul>

        
<p>
这个问题会导致成百上千的 SQL 语句被执行。这通常不是期望的。
        </p>

        
<p>
MyBatis 能延迟加载这样的查询就是一个好处,因此你可以分散这些语句同时运行的消
耗。然而,如果你加载一个列表,之后迅速迭代来访问嵌套的数据,你会调用所有的延迟加
载,这样的行为可能是很糟糕的。
        </p>

        
<p>
所以还有另外一种方法。
        </p>

        </div>
<div class="section">
<h4><a name="a"></a>关联的嵌套结果</h4>

        
<table border="0" class="table table-striped">
          <thead>
            
<tr class="a">
              
<th>属性</th>
              
<th>描述</th>
            </tr>
          </thead>
          <tbody>
            
<tr class="b">
              
<td><tt>resultMap</tt></td>
              
<td>
这是结果映射的 ID,可以映射关联的嵌套结果到一个合适的对象图中。这
是一种替代方法来调用另外一个查询语句。这允许你联合多个表来合成到
resultMap
一个单独的结果集。这样的结果集可能包含重复,数据的重复组需要被分
解,合理映射到一个嵌套的对象图。为了使它变得容易,MyBatis 让你“链
接”结果映射,来处理嵌套结果。一个例子会很容易来仿照,这个表格后
面也有一个示例。
              </td>
            </tr>
            
<tr class="a">
              
<td><tt>columnPrefix</tt></td>
              
<td>
                When joining multiple tables, you would have to use column alias to avoid duplicated
                column names in the ResultSet. Specifying columnPrefix allows you to map such columns
                to an external resultMap. Please see the example explained later in this section.
              </td>
            </tr>
            
<tr class="b">
              
<td><tt>notNullColumn</tt></td>
              
<td>
                By default a child object is created only if at least one of the columns mapped to the child's properties 
                is non null. With this attribute you can change this behaviour by specifiying which columns must have a value
                so MyBatis will create a child object only if any of those columns is not null. Multiple column names can be 
                specified using a comma as a separator. Default value: unset.
              </td>
            </tr>            
            
<tr class="a">
              
<td><tt>autoMapping</tt></td>
              
<td>If present, MyBatis will enable or disable auto-mapping when mapping the result to this property.
                This attribute overrides the global autoMappingBehavior.
                Note that it has no effect on an external resultMap, so it is pointless to use it with <tt>select</tt> or <tt>resultMap</tt> attribute. Default value: unset.
              </td>
            </tr>
          </tbody>
        </table>

        
<p>
在上面你已经看到了一个非常复杂的嵌套关联的示例。
下面这个是一个非常简单的示例
来说明它如何工作。代替了执行一个分离的语句,我们联合博客表和作者表在一起,就像:
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;select</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"selectBlog"</span><span class="pln"> </span><span class="atn">resultMap</span><span class="pun">=</span><span class="atv">"blogResult"</span><span class="tag">&gt;</span><span class="pln">
  select
    B.id            as blog_id,
    B.title         as blog_title,
    B.author_id     as blog_author_id,
    A.id            as author_id,
    A.username      as author_username,
    A.password      as author_password,
    A.email         as author_email,
    A.bio           as author_bio
  from Blog B left outer join Author A on B.author_id = A.id
  where B.id = #{id}
</span><span class="tag">&lt;/select&gt;</span></pre></div>

        
<p>
注意这个联合查询, 以及采取保护来确保所有结果被唯一而且清晰的名字来重命名。
这使得映射非常简单。现在我们可以映射这个结果:
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;resultMap</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"blogResult"</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"Blog"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;id</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"blog_id"</span><span class="pln"> </span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"title"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"blog_title"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;association</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"author"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"blog_author_id"</span><span class="pln"> </span><span class="atn">javaType</span><span class="pun">=</span><span class="atv">"Author"</span><span class="pln"> </span><span class="atn">resultMap</span><span class="pun">=</span><span class="atv">"authorResult"</span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;/resultMap&gt;</span><span class="pln">

</span><span class="tag">&lt;resultMap</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"authorResult"</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"Author"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;id</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_id"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"username"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_username"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"password"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_password"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"email"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_email"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"bio"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_bio"</span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;/resultMap&gt;</span></pre></div>

        
<p>
在上面的示例中你可以看到博客的作者关联代表着“authorResult”结果映射来加载作
者实例。
        </p>

        
<p>
          <span class="important">非常重要</span>: 在嵌套据诶过映射中 id 元素扮演了非常重要的角色。应应该通常指定一个
或多个属性,它们可以用来唯一标识结果。实际上就是如果你离开她了,但是有一个严重的
性能问题时 MyBatis 仍然可以工作。选择的属性越少越好,它们可以唯一地标识结果。主键
就是一个显而易见的选择(尽管是联合主键)。
        </p>

        
<p>
现在,上面的示例用了外部的结果映射元素来映射关联。这使得 Author 结果映射可以
重用。然而,如果你不需要重用它的话,或者你仅仅引用你所有的结果映射合到一个单独描
述的结果映射中。你可以嵌套结果映射。这里给出使用这种方式的相同示例:
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;resultMap</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"blogResult"</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"Blog"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;id</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"blog_id"</span><span class="pln"> </span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"title"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"blog_title"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;association</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"author"</span><span class="pln"> </span><span class="atn">javaType</span><span class="pun">=</span><span class="atv">"Author"</span><span class="tag">&gt;</span><span class="pln">
    </span><span class="tag">&lt;id</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_id"</span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"username"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_username"</span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"password"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_password"</span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"email"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_email"</span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"bio"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_bio"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;/association&gt;</span><span class="pln">
</span><span class="tag">&lt;/resultMap&gt;</span></pre></div>

        
<p>
          What if the blog has a co-author?
          The select statement would look like:
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;select</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"selectBlog"</span><span class="pln"> </span><span class="atn">resultMap</span><span class="pun">=</span><span class="atv">"blogResult"</span><span class="tag">&gt;</span><span class="pln">
  select
    B.id            as blog_id,
    B.title         as blog_title,
    A.id            as author_id,
    A.username      as author_username,
    A.password      as author_password,
    A.email         as author_email,
    A.bio           as author_bio,
    CA.id           as co_author_id,
    CA.username     as co_author_username,
    CA.password     as co_author_password,
    CA.email        as co_author_email,
    CA.bio          as co_author_bio
  from Blog B
  left outer join Author A on B.author_id = A.id
  left outer join Author CA on B.co_author_id = CA.id
  where B.id = #{id}
</span><span class="tag">&lt;/select&gt;</span></pre></div>

        
<p>
          Recall that the resultMap for Author is defined as follows.
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;resultMap</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"authorResult"</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"Author"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;id</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_id"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"username"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_username"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"password"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_password"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"email"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_email"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"bio"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_bio"</span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;/resultMap&gt;</span></pre></div>

        
<p>
          Because the column names in the results differ from the columns defined in the resultMap,
          you need to specify <tt>columnPrefix</tt> to reuse the resultMap for mapping co-author results.
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;resultMap</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"blogResult"</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"Blog"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;id</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"blog_id"</span><span class="pln"> </span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"title"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"blog_title"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;association</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"author"</span><span class="pln">
    </span><span class="atn">resultMap</span><span class="pun">=</span><span class="atv">"authorResult"</span><span class="pln"> </span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;association</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"coAuthor"</span><span class="pln">
    </span><span class="atn">resultMap</span><span class="pun">=</span><span class="atv">"authorResult"</span><span class="pln">
    </span><span class="atn">columnPrefix</span><span class="pun">=</span><span class="atv">"co_"</span><span class="pln"> </span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;/resultMap&gt;</span></pre></div>

        
<p>
上面你已经看到了如何处理“有一个”类型关联。但是“有很多个”是怎样的?下面这
个部分就是来讨论这个主题的。
        </p>

        </div>
<div class="section">
<h4><a name="a"></a>集合</h4>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;collection</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"posts"</span><span class="pln"> </span><span class="atn">ofType</span><span class="pun">=</span><span class="atv">"domain.blog.Post"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;id</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"post_id"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"subject"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"post_subject"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"body"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"post_body"</span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;/collection&gt;</span></pre></div>

        
<p>
集合元素的作用几乎和关联是相同的。实际上,它们也很相似,文档的异同是多余的。
所以我们更多关注于它们的不同。
        </p>

        
<p>
我们来继续上面的示例,一个博客只有一个作者。但是博客有很多文章。在博客类中,
这可以由下面这样的写法来表示:
        </p>

        
<div class="source"><pre class="prettyprint"><span class="kwd">private</span><span class="pln"> </span><span class="typ">List</span><span class="pun">&lt;</span><span class="typ">Post</span><span class="pun">&gt;</span><span class="pln"> posts</span><span class="pun">;</span></pre></div>

        
<p>
要映射嵌套结果集合到 List 中,我们使用集合元素。就像关联元素一样,我们可以从
连接中使用嵌套查询,或者嵌套结果。
        </p>

        </div>
<div class="section">
<h4><a name="a"></a>集合的嵌套查询</h4>

        
<p>
首先,让我们看看使用嵌套查询来为博客加载文章。
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;resultMap</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"blogResult"</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"Blog"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;collection</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"posts"</span><span class="pln"> </span><span class="atn">javaType</span><span class="pun">=</span><span class="atv">"ArrayList"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">ofType</span><span class="pun">=</span><span class="atv">"Post"</span><span class="pln"> </span><span class="atn">select</span><span class="pun">=</span><span class="atv">"selectPostsForBlog"</span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;/resultMap&gt;</span><span class="pln">

</span><span class="tag">&lt;select</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"selectBlog"</span><span class="pln"> </span><span class="atn">resultMap</span><span class="pun">=</span><span class="atv">"blogResult"</span><span class="tag">&gt;</span><span class="pln">
  SELECT * FROM BLOG WHERE ID = #{id}
</span><span class="tag">&lt;/select&gt;</span><span class="pln">

</span><span class="tag">&lt;select</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"selectPostsForBlog"</span><span class="pln"> </span><span class="atn">resultType</span><span class="pun">=</span><span class="atv">"Blog"</span><span class="tag">&gt;</span><span class="pln">
  SELECT * FROM POST WHERE BLOG_ID = #{id}
</span><span class="tag">&lt;/select&gt;</span></pre></div>

        
<p>
这里你应该注意很多东西,但大部分代码和上面的关联元素是非常相似的。首先,你应
该注意我们使用的是集合元素。然后要注意那个新的“ofType”属性。这个属性用来区分
JavaBean(或字段)属性类型和集合包含的类型来说是很重要的。所以你可以读出下面这个
映射:
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;collection</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"posts"</span><span class="pln"> </span><span class="atn">javaType</span><span class="pun">=</span><span class="atv">"ArrayList"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">ofType</span><span class="pun">=</span><span class="atv">"Post"</span><span class="pln"> </span><span class="atn">select</span><span class="pun">=</span><span class="atv">"selectPostsForBlog"</span><span class="tag">/&gt;</span></pre></div>

        
<p>
          <span class="important">读作</span>: “在 Post 类型的 ArrayList 中的 posts 的集合。”
        </p>

        
<p>
javaType 属性是不需要的,因为 MyBatis 在很多情况下会为你算出来。所以你可以缩短
写法:
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;collection</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"posts"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">ofType</span><span class="pun">=</span><span class="atv">"Post"</span><span class="pln"> </span><span class="atn">select</span><span class="pun">=</span><span class="atv">"selectPostsForBlog"</span><span class="tag">/&gt;</span></pre></div>

        </div>
<div class="section">
<h4><a name="a"></a>集合的嵌套结果</h4>

        
<p>
至此,你可以猜测集合的嵌套结果是如何来工作的,因为它和关联完全相同,除了它应
用了一个“ofType”属性
        </p>

        
<p>First, let's look at the SQL:</p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;select</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"selectBlog"</span><span class="pln"> </span><span class="atn">resultMap</span><span class="pun">=</span><span class="atv">"blogResult"</span><span class="tag">&gt;</span><span class="pln">
  select
  B.id as blog_id,
  B.title as blog_title,
  B.author_id as blog_author_id,
  P.id as post_id,
  P.subject as post_subject,
  P.body as post_body,
  from Blog B
  left outer join Post P on B.id = P.blog_id
  where B.id = #{id}
</span><span class="tag">&lt;/select&gt;</span></pre></div>

        
<p>
我们又一次联合了博客表和文章表,而且关注于保证特性,结果列标签的简单映射。现
在用文章映射集合映射博客,可以简单写为:
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;resultMap</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"blogResult"</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"Blog"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;id</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"blog_id"</span><span class="pln"> </span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"title"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"blog_title"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;collection</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"posts"</span><span class="pln"> </span><span class="atn">ofType</span><span class="pun">=</span><span class="atv">"Post"</span><span class="tag">&gt;</span><span class="pln">
    </span><span class="tag">&lt;id</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"post_id"</span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"subject"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"post_subject"</span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"body"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"post_body"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;/collection&gt;</span><span class="pln">
</span><span class="tag">&lt;/resultMap&gt;</span></pre></div>

        
<p>
同样,要记得 id 元素的重要性,如果你不记得了,请阅读上面的关联部分。
        </p>

        
<p>
同样,
如果你引用更长的形式允许你的结果映射的更多重用,
你可以使用下面这个替代
的映射:
        </p>
        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;resultMap</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"blogResult"</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"Blog"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;id</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"blog_id"</span><span class="pln"> </span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"title"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"blog_title"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;collection</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"posts"</span><span class="pln"> </span><span class="atn">ofType</span><span class="pun">=</span><span class="atv">"Post"</span><span class="pln"> </span><span class="atn">resultMap</span><span class="pun">=</span><span class="atv">"blogPostResult"</span><span class="pln"> </span><span class="atn">columnPrefix</span><span class="pun">=</span><span class="atv">"post_"</span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;/resultMap&gt;</span><span class="pln">

</span><span class="tag">&lt;resultMap</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"blogPostResult"</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"Post"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;id</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"id"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"subject"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"subject"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"body"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"body"</span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;/resultMap&gt;</span></pre></div>

        
<p>
          <span class="label important">注意</span> 这个对你所映射的内容没有深度,广度或关联和集合相联合的限制。当映射它们
时你应该在大脑中保留它们的表现。
你的应用在找到最佳方法前要一直进行的单元测试和性
能测试。好在 myBatis 让你后来可以改变想法,而不对你的代码造成很小(或任何)影响。
        </p>

        
<p>
高级关联和集合映射是一个深度的主题。文档只能给你介绍到这了。加上一点联系,你
会很快清楚它们的用法。
        </p>

        </div>
<div class="section">
<h4><a name="a"></a>鉴别器</h4>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;discriminator</span><span class="pln"> </span><span class="atn">javaType</span><span class="pun">=</span><span class="atv">"int"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"draft"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;case</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"1"</span><span class="pln"> </span><span class="atn">resultType</span><span class="pun">=</span><span class="atv">"DraftPost"</span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;/discriminator&gt;</span></pre></div>

        
<p>
有时一个单独的数据库查询也许返回很多不同
(但是希望有些关联)
数据类型的结果集。
鉴别器元素就是被设计来处理这个情况的,
还有包括类的继承层次结构。
鉴别器非常容易理
解,因为它的表现很像 Java 语言中的 switch 语句。
        </p>

        
<p>
定义鉴别器指定了 column 和 javaType 属性。
列是 MyBatis 查找比较值的地方。
JavaType
是需要被用来保证等价测试的合适类型(尽管字符串在很多情形下都会有用)。比如:
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;resultMap</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"vehicleResult"</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"Vehicle"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;id</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"vin"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"vin"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"year"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"year"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"make"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"make"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"model"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"model"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"color"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"color"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;discriminator</span><span class="pln"> </span><span class="atn">javaType</span><span class="pun">=</span><span class="atv">"int"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"vehicle_type"</span><span class="tag">&gt;</span><span class="pln">
    </span><span class="tag">&lt;case</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"1"</span><span class="pln"> </span><span class="atn">resultMap</span><span class="pun">=</span><span class="atv">"carResult"</span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;case</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"2"</span><span class="pln"> </span><span class="atn">resultMap</span><span class="pun">=</span><span class="atv">"truckResult"</span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;case</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"3"</span><span class="pln"> </span><span class="atn">resultMap</span><span class="pun">=</span><span class="atv">"vanResult"</span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;case</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"4"</span><span class="pln"> </span><span class="atn">resultMap</span><span class="pun">=</span><span class="atv">"suvResult"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;/discriminator&gt;</span><span class="pln">
</span><span class="tag">&lt;/resultMap&gt;</span></pre></div>

        
<p>
在这个示例中,
MyBatis 会从结果集中得到每条记录,
然后比较它的 vehicle 类型的值。
如果它匹配任何一个鉴别器的实例,那么就使用这个实例指定的结果映射。换句话说,这样
做完全是剩余的结果映射被忽略(除非它被扩展,这在第二个示例中讨论)
。如果没有任何
一个实例相匹配,那么 MyBatis 仅仅使用鉴别器块外定义的结果映射。所以,如果 carResult
按如下声明:
        </p>


        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;resultMap</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"carResult"</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"Car"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"doorCount"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"door_count"</span><span class="pln"> </span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;/resultMap&gt;</span></pre></div>

        
<p>
那么只有 doorCount 属性会被加载。这步完成后完整地允许鉴别器实例的独立组,尽管
和父结果映射可能没有什么关系。这种情况下,我们当然知道 cars 和 vehicles 之间有关系,
如 Car 是一个 Vehicle 实例。因此,我们想要剩余的属性也被加载。我们设置的结果映射的
简单改变如下。
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;resultMap</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"carResult"</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"Car"</span><span class="pln"> </span><span class="atn">extends</span><span class="pun">=</span><span class="atv">"vehicleResult"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"doorCount"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"door_count"</span><span class="pln"> </span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;/resultMap&gt;</span></pre></div>

        
<p>
现在 vehicleResult 和 carResult 的属性都会被加载了。
        </p>

        
<p>
尽管曾经有些人会发现这个外部映射定义会多少有一些令人厌烦之处。
因此还有另外一
种语法来做简洁的映射风格。比如:
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;resultMap</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"vehicleResult"</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"Vehicle"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;id</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"id"</span><span class="pln"> </span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"vin"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"vin"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"year"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"year"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"make"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"make"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"model"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"model"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"color"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"color"</span><span class="tag">/&gt;</span><span class="pln">
  </span><span class="tag">&lt;discriminator</span><span class="pln"> </span><span class="atn">javaType</span><span class="pun">=</span><span class="atv">"int"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"vehicle_type"</span><span class="tag">&gt;</span><span class="pln">
    </span><span class="tag">&lt;case</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"1"</span><span class="pln"> </span><span class="atn">resultType</span><span class="pun">=</span><span class="atv">"carResult"</span><span class="tag">&gt;</span><span class="pln">
      </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"doorCount"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"door_count"</span><span class="pln"> </span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;/case&gt;</span><span class="pln">
    </span><span class="tag">&lt;case</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"2"</span><span class="pln"> </span><span class="atn">resultType</span><span class="pun">=</span><span class="atv">"truckResult"</span><span class="tag">&gt;</span><span class="pln">
      </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"boxSize"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"box_size"</span><span class="pln"> </span><span class="tag">/&gt;</span><span class="pln">
      </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"extendedCab"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"extended_cab"</span><span class="pln"> </span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;/case&gt;</span><span class="pln">
    </span><span class="tag">&lt;case</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"3"</span><span class="pln"> </span><span class="atn">resultType</span><span class="pun">=</span><span class="atv">"vanResult"</span><span class="tag">&gt;</span><span class="pln">
      </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"powerSlidingDoor"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"power_sliding_door"</span><span class="pln"> </span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;/case&gt;</span><span class="pln">
    </span><span class="tag">&lt;case</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"4"</span><span class="pln"> </span><span class="atn">resultType</span><span class="pun">=</span><span class="atv">"suvResult"</span><span class="tag">&gt;</span><span class="pln">
      </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"allWheelDrive"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"all_wheel_drive"</span><span class="pln"> </span><span class="tag">/&gt;</span><span class="pln">
    </span><span class="tag">&lt;/case&gt;</span><span class="pln">
  </span><span class="tag">&lt;/discriminator&gt;</span><span class="pln">
</span><span class="tag">&lt;/resultMap&gt;</span></pre></div>

        
<p>
          <span class="label important">要记得</span> 这些都是结果映射,
如果你不指定任何结果,
那么 MyBatis 将会为你自动匹配列
和属性。所以这些例子中的大部分是很冗长的,而其实是不需要的。也就是说,很多数据库
是很复杂的,我们不太可能对所有示例都能依靠它。
        </p>

      </div></div>
      
      <a name="Auto-mapping"></a>
<div class="section" id="Auto-mapping">
<h3><a name="a"></a>自动映射</h3>

        
<p>
           正如你在前面一节看到的，在简单的场景下，MyBatis可以替你自动映射查询结果。
           如果遇到复杂的场景，你需要构建一个result map。
           但是在本节你将看到，你也可以混合使用这两种策略。
           让我们到深一点的层面上看看自动映射是怎样工作的。
        </p>

        
<p>
           当自动映射查询结果时，MyBatis会获取sql返回的列名并在java类中查找相同名字的属性（忽略大小写）。
           这意味着如果Mybatis发现了<i>ID</i>列和<i>id</i>属性，Mybatis会将<i>ID</i>的值赋给<i>id</i>。
        </p>

        
<p>
           通常数据库列使用大写单词命名，单词间用下划线分隔；而java属性一般遵循驼峰命名法。
           为了在这两种命名方式之间启用自动映射，需要将 <tt>mapUnderscoreToCamelCase</tt>设置为true。
        </p>
        
        
<p>
           自动映射甚至在特定的result map下也能工作。在这种情况下，对于每一个result map,所有的ResultSet提供的列，
           如果没有被手工映射，则将被自动映射。自动映射处理完毕后手工映射才会被处理。
           在接下来的例子中， <i>id</i> 和 <i>userName</i>列将被自动映射， <i>hashed_password</i> 列将根据配置映射。
        </p>
        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;select</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"selectUsers"</span><span class="pln"> </span><span class="atn">resultMap</span><span class="pun">=</span><span class="atv">"userResultMap"</span><span class="tag">&gt;</span><span class="pln">
  select
    user_id             as "id",
    user_name           as "userName",
    hashed_password
  from some_table
  where id = #{id}
</span><span class="tag">&lt;/select&gt;</span></pre></div>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;resultMap</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"userResultMap"</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"User"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"password"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"hashed_password"</span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;/resultMap&gt;</span></pre></div>

        
<p>
          There are three auto-mapping levels:
        </p>
        
        
<ul>
          
<li>
            <tt>NONE</tt> - disables auto-mapping. Only manually mapped properties will be set.
          </li>
          
<li>
            <tt>PARTIAL</tt> - will auto-map results except those that have nested result mappings defined inside (joins).
          </li>
          
<li>
            <tt>FULL</tt> - auto-maps everything.
          </li>
        </ul>

        
<p>
          The default value is <tt>PARTIAL</tt>, and it is so for a reason. When <tt>FULL</tt> is used auto-mapping will
          be performed when processing join results and joins retrieve data of several different entities in the same row 
          hence this may result in undesired mappings. To understand the risk have a look at the following sample:
        </p>
        
        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;select</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"selectBlog"</span><span class="pln"> </span><span class="atn">resultMap</span><span class="pun">=</span><span class="atv">"blogResult"</span><span class="tag">&gt;</span><span class="pln">
  select
    B.id,
    B.title,
    A.username,
  from Blog B left outer join Author A on B.author_id = A.id
  where B.id = #{id}
</span><span class="tag">&lt;/select&gt;</span></pre></div>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;resultMap</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"blogResult"</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"Blog"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;association</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"author"</span><span class="pln"> </span><span class="atn">resultMap</span><span class="pun">=</span><span class="atv">"authorResult"</span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;/resultMap&gt;</span><span class="pln">

</span><span class="tag">&lt;resultMap</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"authorResult"</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"Author"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"username"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"author_username"</span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;/resultMap&gt;</span></pre></div>
        
        
<p>
          With this result map both <i>Blog</i> and <i>Author</i> will be auto-mapped. But note that <i>Author</i> has an <i>id</i> 
          property and there is a column named <i>id</i> in the ResultSet so Author's id will be filled with Blog's id, and that is not 
          what you were expecting. So use the <tt>FULL</tt> option with caution.
        </p>

        
<p>
          Regardless of the auto-mapping level configured you can enable or disable the automapping for an specific ResultMap
          by adding the attribute <tt>autoMapping</tt> to it:
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;resultMap</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"userResultMap"</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"User"</span><span class="pln"> </span><span class="atn">autoMapping</span><span class="pun">=</span><span class="atv">"false"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;result</span><span class="pln"> </span><span class="atn">property</span><span class="pun">=</span><span class="atv">"password"</span><span class="pln"> </span><span class="atn">column</span><span class="pun">=</span><span class="atv">"hashed_password"</span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;/resultMap&gt;</span></pre></div>
              
      </div>
      
      <a name="cache"></a>
<div class="section" id="cache">
<h3><a name="a"></a>缓存</h3>
        
<p>
MyBatis 包含一个非常强大的查询缓存特性,它可以非常方便地配置和定制。MyBatis 3
中的缓存实现的很多改进都已经实现了,使得它更加强大而且易于配置。
        </p>

        
<p>
默认情况下是没有开启缓存的,除了局部的 session 缓存,可以增强变现而且处理循环
依赖也是必须的。要开启二级缓存,你需要在你的 SQL 映射文件中添加一行:
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;cache/&gt;</span></pre></div>

        
<p>
字面上看就是这样。这个简单语句的效果如下:
        </p>

        
<ul>
          
<li>映射语句文件中的所有 select 语句将会被缓存。</li>
          
<li>映射语句文件中的所有 insert,update 和 delete 语句会刷新缓存。</li>
          
<li>缓存会使用 Least Recently Used(LRU,最近最少使用的)算法来收回。</li>
          
<li>根据时间表(比如 no Flush Interval,没有刷新间隔), 缓存不会以任何时间顺序 来刷新。</li>
          
<li>缓存会存储列表集合或对象(无论查询方法返回什么)的 1024 个引用。</li>
          
<li>
缓存会被视为是 read/write(可读/可写)的缓存,意味着对象检索不是共享的,而
且可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。
          </li>
        </ul>

        
<p>
所有的这些属性都可以通过缓存元素的属性来修改。比如:
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;cache</span><span class="pln">
  </span><span class="atn">eviction</span><span class="pun">=</span><span class="atv">"FIFO"</span><span class="pln">
  </span><span class="atn">flushInterval</span><span class="pun">=</span><span class="atv">"60000"</span><span class="pln">
  </span><span class="atn">size</span><span class="pun">=</span><span class="atv">"512"</span><span class="pln">
  </span><span class="atn">readOnly</span><span class="pun">=</span><span class="atv">"true"</span><span class="tag">/&gt;</span></pre></div>

        
<p>
这个更高级的配置创建了一个 FIFO 缓存,并每隔 60 秒刷新,存数结果对象或列表的
512 个引用,而且返回的对象被认为是只读的,因此在不同线程中的调用者之间修改它们会
导致冲突。
        </p>

        
<p>
可用的收回策略有:
        </p>

        
<ul>
          
<li>
            <tt>LRU</tt> – 最近最少使用的:移除最长时间不被使用的对象。

          </li>
          
<li><tt>FIFO</tt> – 先进先出:按对象进入缓存的顺序来移除它们。
          </li>
          
<li>
            <tt>SOFT</tt> – 软引用:移除基于垃圾回收器状态和软引用规则的对象。
          </li>
          
<li>
            <tt>WEAK</tt> – 弱引用:更积极地移除基于垃圾收集器状态和弱引用规则的对象。
          </li>
        </ul>

        
<p>默认的是 LRU。</p>

        
<p>
flushInterval(刷新间隔)可以被设置为任意的正整数,而且它们代表一个合理的毫秒
形式的时间段。默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用语句时刷新。
        </p>

        
<p>
size(引用数目)可以被设置为任意正整数,要记住你缓存的对象数目和你运行环境的
可用内存资源数目。默认值是 1024。
        </p>

        
<p>
readOnly(只读)属性可以被设置为 true 或 false。只读的缓存会给所有调用者返回缓
存对象的相同实例。因此这些对象不能被修改。这提供了很重要的性能优势。可读写的缓存
会返回缓存对象的拷贝(通过序列化)
。这会慢一些,但是安全,因此默认是 false。
        </p>

        
<div class="section">
<h4><a name="a"></a>使用自定义缓存</h4>

        
<p>
除了这些自定义缓存的方式,
你也可以通过实现你自己的缓存或为其他第三方缓存方案
创建适配器来完全覆盖缓存行为。
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;cache</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"com.domain.something.MyCustomCache"</span><span class="tag">/&gt;</span></pre></div>

        
<p>
这个示 例展 示了 如何 使用 一个 自定义 的缓 存实 现。type 属 性指 定的 类必 须实现
org.mybatis.cache.Cache 接口。这个接口是 MyBatis 框架中很多复杂的接口之一,但是简单
给定它做什么就行。
        </p>

        
<div class="source"><pre class="prettyprint"><span class="kwd">public</span><span class="pln"> </span><span class="kwd">interface</span><span class="pln"> </span><span class="typ">Cache</span><span class="pln"> </span><span class="pun">{</span><span class="pln">
  </span><span class="typ">String</span><span class="pln"> getId</span><span class="pun">();</span><span class="pln">
  </span><span class="kwd">int</span><span class="pln"> getSize</span><span class="pun">();</span><span class="pln">
  </span><span class="kwd">void</span><span class="pln"> putObject</span><span class="pun">(</span><span class="typ">Object</span><span class="pln"> key</span><span class="pun">,</span><span class="pln"> </span><span class="typ">Object</span><span class="pln"> value</span><span class="pun">);</span><span class="pln">
  </span><span class="typ">Object</span><span class="pln"> getObject</span><span class="pun">(</span><span class="typ">Object</span><span class="pln"> key</span><span class="pun">);</span><span class="pln">
  </span><span class="kwd">boolean</span><span class="pln"> hasKey</span><span class="pun">(</span><span class="typ">Object</span><span class="pln"> key</span><span class="pun">);</span><span class="pln">
  </span><span class="typ">Object</span><span class="pln"> removeObject</span><span class="pun">(</span><span class="typ">Object</span><span class="pln"> key</span><span class="pun">);</span><span class="pln">
  </span><span class="kwd">void</span><span class="pln"> clear</span><span class="pun">();</span><span class="pln">
</span><span class="pun">}</span></pre></div>

        
<p>
要配置你的缓存,
简单和公有的 JavaBeans 属性来配置你的缓存实现,
而且是通过 cache
元素来传递属性,
比如,
下面代码会在你的缓存实现中调用一个称为
“setCacheFile(String file)”
的方法:
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;cache</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"com.domain.something.MyCustomCache"</span><span class="tag">&gt;</span><span class="pln">
  </span><span class="tag">&lt;property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"cacheFile"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"/tmp/my-custom-cache.tmp"</span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;/cache&gt;</span></pre></div>

        
<p>
你可以使用所有简单类型作为 JavaBeans 的属性,MyBatis 会进行转换。
        </p>

        
<p>
记得缓存配置和缓存实例是绑定在 SQL 映射文件的命名空间是很重要的。因此,所有
在相同命名空间的语句正如绑定的缓存一样。
语句可以修改和缓存交互的方式,
或在语句的
语句的基础上使用两种简单的属性来完全排除它们。默认情况下,语句可以这样来配置:
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;select</span><span class="pln"> ... </span><span class="atn">flushCache</span><span class="pun">=</span><span class="atv">"false"</span><span class="pln"> </span><span class="atn">useCache</span><span class="pun">=</span><span class="atv">"true"</span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;insert</span><span class="pln"> ... </span><span class="atn">flushCache</span><span class="pun">=</span><span class="atv">"true"</span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;update</span><span class="pln"> ... </span><span class="atn">flushCache</span><span class="pun">=</span><span class="atv">"true"</span><span class="tag">/&gt;</span><span class="pln">
</span><span class="tag">&lt;delete</span><span class="pln"> ... </span><span class="atn">flushCache</span><span class="pun">=</span><span class="atv">"true"</span><span class="tag">/&gt;</span></pre></div>

        
<p>
因为那些是默认的,你明显不能明确地以这种方式来配置一条语句。相反,如果你想改
变默认的行为,只能设置 flushCache 和 useCache 属性。比如,在一些情况下你也许想排除
从缓存中查询特定语句结果,或者你也许想要一个查询语句来刷新缓存。相似地,你也许有
一些更新语句依靠执行而不需要刷新缓存。
        </p>

          </div>
<div class="section">
<h4><a name="a"></a>参照缓存</h4>
        
<p>
回想一下上一节内容,
这个特殊命名空间的唯一缓存会被使用或者刷新相同命名空间内
的语句。也许将来的某个时候,你会想在命名空间中共享相同的缓存配置和实例。在这样的
情况下你可以使用 cache-ref 元素来引用另外一个缓存。
        </p>

        
<div class="source"><pre class="prettyprint"><span class="tag">&lt;cache-ref</span><span class="pln"> </span><span class="atn">namespace</span><span class="pun">=</span><span class="atv">"com.someone.application.data.SomeMapper"</span><span class="tag">/&gt;</span></pre></div>
      </div></div>
    </div>
  

                  </div>
            </div>
          </div>

    <hr>

    <footer>
            <div class="container-fluid">
                      <div class="row-fluid">
                                      <p>Copyright ©                    2009–2016
                        <a href="http://www.mybatis.org/">MyBatis.org</a>.
            All rights reserved.    
      </p>
                </div>

        
                </div>
    </footer>
        

</body></html>